﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Retete.Models;
using Retete.ViewModels;

namespace Retete.Controllers
{
    public class MeniuriController : Controller
    {
        private ReteteEntities entities = new ReteteEntities();

        public ActionResult Index(int? year, int? month, int? day)
        {
            if (day.HasValue == true)
            {
                DateTime selectedDate = new DateTime(year.Value, month.Value, day.Value);
                List<Meniu> selectieMeniuri = entities.Meniuri.Where(element => element.Valabilitate.Value == selectedDate.Date || element.Valabilitate.HasValue == false).ToList();

                return View(new MeniuriViewModel(selectieMeniuri, selectedDate));
            }
            else
            {
                List<Meniu> selectieMeniuri = entities.Meniuri.Where(element => element.Valabilitate.Value == DateTime.Today || element.Valabilitate.HasValue == false).ToList();
                return View(new MeniuriViewModel(selectieMeniuri, DateTime.Today));
            }
        }
        public ActionResult Create()
        {
            Meniu selectie = entities.Meniuri.OrderByDescending(element => element.Cod).FirstOrDefault();

            if (string.IsNullOrEmpty(Request["SelectedDate"]) == false)
            {
                DateTime selectedDate = DateTime.Parse(Request["SelectedDate"].ToString());

                if (selectie == null) return View(new MeniuViewModel() { MeniuNouValabilitate = selectedDate });
                else return View(new MeniuViewModel() { MeniuNouValabilitate = selectedDate, CodUltimulMeniu = selectie.Cod });
            }
            else if (selectie == null) return View(new MeniuViewModel());
            else return View(new MeniuViewModel() { CodUltimulMeniu = selectie.Cod });
        }
        public ActionResult Edit(int id)
        {
            Meniu meniu = entities.Meniuri.FirstOrDefault(element => element.ID == id);

            if (meniu == null) return RedirectToAction("Index");
            else return View(new MeniuViewModel(meniu));
        }
        public ActionResult SendMailMeniuri()
        {
            int diff = DateTime.Today.DayOfWeek - DayOfWeek.Monday;
            if (diff < 0) diff += 7;
            DateTime primaZiDinSaptamana = DateTime.Today.AddDays(-1 * diff).Date;
            DateTime ultimaZiDinSaptamana = primaZiDinSaptamana.AddDays(7).Date;

            return View(entities.Meniuri.Where(element => element.Valabilitate.HasValue && element.Valabilitate.Value >= primaZiDinSaptamana && element.Valabilitate.Value <= ultimaZiDinSaptamana).OrderBy(element => element.Valabilitate).ToList());
        }

        [HttpPost]
        public ActionResult Index(MeniuriViewModel result)
        {
            Meniu meniu = entities.Meniuri.FirstOrDefault(element => element.ID == result.IDMeniuSters);
            DateTime selectedDate = DateTime.Parse(Request["SelectedDate"].ToString());

            if (meniu != null)
            {
                try
                {
                    entities.DeleteObject(meniu);
                    entities.SaveChanges();
                    result.IDMeniuSters = -1;

                    return RedirectToAction("Index", new { year = selectedDate.Year, month = selectedDate.Month, day = selectedDate.Day });
                }
                catch
                {
                    ModelState.AddModelError(string.Empty, "Meniul nu poate fi sters");
                    return View(result);
                }
            }
            else return RedirectToAction("Index", new { year = selectedDate.Year, month = selectedDate.Month, day = selectedDate.Day });
        }

        [HttpPost]
        public ActionResult Create(MeniuViewModel result)
        {
            if (result.IDRetetaStearsa != -1)
            {
                MeniuReteta retetaStearsa = result.Retete.First(element => element.ID == result.IDRetetaStearsa);
                result.Retete.Remove(retetaStearsa);
                result.IDRetetaStearsa = -1;

                ModelState.Clear();
                return View(result);
            }
            else if (string.IsNullOrEmpty(result.RetetaNouaNume) == false)
            {
                if (result.Retete == null) result.Retete = new List<MeniuReteta>();

                Reteta selectie = entities.Retete.FirstOrDefault(element => element.ID == result.RetetaNouaID);

                result.Retete.Add(new MeniuReteta() { IDReteta = result.RetetaNouaID, Reteta = selectie, Portii = result.RetetaNouaPortii });
                result.RetetaNouaID = 0;
                result.RetetaNouaNume = string.Empty;
                result.RetetaNouaPortii = 0;
                result.FocusRetetaNoua = true;

                ModelState.Clear();
                return View(result);
            }
            else
            {
                if (string.IsNullOrEmpty(result.MeniuNouCod) == true) ModelState.AddModelError("MeniuNouCod", "Codul meniului este obligatoriu");
                if (string.IsNullOrEmpty(result.MeniuNouNume) == true) ModelState.AddModelError("MeniuNouNume", "Numele meniului este obligatoriu");
                if (entities.Meniuri.Any(element => element.Cod == result.MeniuNouCod) == true) ModelState.AddModelError("MeniuNouCod", "Mai exista un meniu cu acelasi cod");

                if (ModelState.IsValid == true)
                {
                    Meniu nou = new Meniu() { Cod = result.MeniuNouCod, Denumire = result.MeniuNouNume, Pret = result.MeniuNouPret, Valabilitate = result.MeniuNouValabilitate };
                    if (result.Retete != null) foreach (MeniuReteta element in result.Retete) nou.Retete.Add(new MeniuReteta() { IDReteta = element.IDReteta, Portii = element.Portii });
                    entities.AddToMeniuri(nou);
                    entities.SaveChanges();

                    return RedirectToAction("Index");
                }
                else return View(result);
            }
        }

        [HttpPost]
        public ActionResult Edit(int id, MeniuViewModel result)
        {
            if (result.IDRetetaStearsa != -1)
            {
                MeniuReteta retetaStearsa = result.Retete.First(element => element.ID == result.IDRetetaStearsa);
                result.Retete.Remove(retetaStearsa);
                result.IDRetetaStearsa = -1;

                ModelState.Clear();
                return View(result);
            }
            else if (result.ClonareMeniu == true)
            {
                Meniu selectie = entities.Meniuri.First(element => element.ID == result.Meniu.ID);
                Meniu clona = new Meniu() { Cod = selectie.Cod, Denumire = selectie.Denumire, Pret = selectie.Pret, Valabilitate = selectie.Valabilitate };
                foreach (MeniuReteta element in selectie.Retete) clona.Retete.Add(new MeniuReteta() { IDReteta = element.IDReteta, Portii = element.Portii });
                entities.AddToMeniuri(clona);

                selectie.Cod = selectie.Cod + " (" + selectie.ID + "!)";
                entities.SaveChanges();
                
                result.ClonareMeniu = false;
                ModelState.Clear();
                return RedirectToAction("Index");
            }
            else if (string.IsNullOrEmpty(result.RetetaNouaNume) == false)
            {
                if (result.Retete == null) result.Retete = new List<MeniuReteta>();

                Reteta selectie = entities.Retete.FirstOrDefault(element => element.ID == result.RetetaNouaID);

                result.Retete.Add(new MeniuReteta() { IDReteta = result.RetetaNouaID, Reteta = selectie, Portii = result.RetetaNouaPortii });
                result.RetetaNouaID = 0;
                result.RetetaNouaNume = string.Empty;
                result.RetetaNouaPortii = 0;
                result.FocusRetetaNoua = true;

                ModelState.Clear();
                return View(result);
            }
            else
            {
                if (string.IsNullOrEmpty(result.Meniu.Cod) == true) ModelState.AddModelError("MeniuNouCod", "Codul meniului este obligatoriu");
                if (string.IsNullOrEmpty(result.Meniu.Denumire) == true) ModelState.AddModelError("MeniuNouNume", "Numele meniului este obligatoriu");
                if (entities.Meniuri.Any(element => element.ID != result.Meniu.ID && element.Cod == result.Meniu.Cod) == true) ModelState.AddModelError("MeniuNouCod", "Mai exista un meniu cu acelasi cod");

                if (ModelState.IsValid == true)
                {
                    Meniu selectie = entities.Meniuri.First(element => element.ID == id);

                    selectie.Denumire = result.Meniu.Denumire;
                    selectie.Pret = result.Meniu.Pret;
                    selectie.Valabilitate = result.Meniu.Valabilitate;

                    while (selectie.Retete.Count > 0) entities.DeleteObject(selectie.Retete.First());
                    if (result.Retete != null) foreach (MeniuReteta element in result.Retete) entities.MeniuriRetete.AddObject(new MeniuReteta() { IDMeniu = id, IDReteta = element.IDReteta, Portii = element.Portii });
                    entities.SaveChanges();

                    return RedirectToAction("Index");
                }
                else return View(result);
            }
        }

        [HttpPost]
        public ActionResult SendMailMeniuri(List<Meniu> result)
        {
            return RedirectToAction("Index");
        }
    }
}